/**
 * 
 */
package cn.ivicar.sim.servlet;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.ivicar.app.guice.AppGuiceConfig;
import cn.ivicar.sim.controller.SimController;
import weixin.popular.bean.paymch.MchBaseResult;
import weixin.popular.util.StreamUtils;
import weixin.popular.util.XMLConverUtil;

/**
 * 微信支付回调
 * 
 * @author liurunbin 2017年6月23日 cn.ivicar.pay.servlet
 */
public class WechatPayNotifyServlet extends HttpServlet {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(WechatPayNotifyServlet.class);

	private static final long serialVersionUID = 1L;

	private SimController simController = AppGuiceConfig.getStaticInjector().getInstance(SimController.class);

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取请求数据
		String xmlData = StreamUtils.copyToString(request.getInputStream(), Charset.forName("utf-8"));
		LOGGER.info("收到微信支付回调 ：" + xmlData);
		// 将XML转为MAP,确保所有字段都参与签名验证
		Map<String, String> mapData = XMLConverUtil.convertToMap(xmlData);

		//TODO: 微信回调去重处理

		try {
			simController.callBack(mapData);
			//expireKey.add(mapData.get("transaction_id"));
			MchBaseResult baseResult = new MchBaseResult();
			baseResult.setReturn_code("SUCCESS");
			baseResult.setReturn_msg("OK");
			response.getOutputStream().write(XMLConverUtil.convertToXML(baseResult).getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			MchBaseResult baseResult = new MchBaseResult();
			baseResult.setReturn_code("FAIL");
			baseResult.setReturn_msg("ERROR");
			response.getOutputStream().write(XMLConverUtil.convertToXML(baseResult).getBytes());

		}

	}

}
